/* The javascript file for luckydraw. */

let currentItem = 0;
let time;
let times = 0;

function sleep(time) {
    return new Promise(reslove => {
        setTimeout(reslove, delay);
    });
}

function PlayOrPause() {
    var player = document.getElementsByTagName('audio')[0];
    if (player.paused == true)
        player.play();
    else
        player.pause();
}

function GetRandom() { // Get the random number.
    var number = Math.ceil(Math.random()*100);
    var result;
    if (number <= 3)
        result = 1;
    else if(number > 3 && number <= 12)
        result = 2;
    else if(number > 12 && number <= 27)
        result = 3;
    else if(number > 27 && number <= 47)
        result = 4;
    else if(number > 47 && number <= 72)
        result = 5;
    else
        result = 6;
    return result;
}

function SelectItem(num, action) {
    var itemObject = document.getElementById('prize-' + num);
    var color, shadow;
    if (action == 1) {
        color = "yellow";
        shadow = "0 0 8px 10px rgba(250, 200, 55, .3)";
    } else {
        color = "white";
        shadow = "none";
    }
    itemObject.style.cssText += "border-color: " + color + ";" + "box-shadow: " + shadow;
}

function ChangeItem() {
    if (currentItem == 6) {
        currentItem = 1;
        times++;
    } else
        currentItem++;
}

function Start() {
    (async function () {
        setTimeout(function () {
            document.getElementsByTagName("button")[1].blur(); 
        }, 500);
    })();

    if (time != null) {
        clearInterval(time);
        times = 0;
        time = null;
        for (i = 1; i <= 6; i++) {
            SelectItem(i, 0);
        }
        return;
    }

    var prize = GetRandom();

    if (currentItem != 0) {
        SelectItem(currentItem, 0);
        currentItem = 0;
    }
    ChangeItem();
    SelectItem(currentItem, 1);

    // Start luckydraw
        time = setInterval(function () {
            SelectItem(currentItem, 0);
            ChangeItem();
            SelectItem(currentItem, 1);
            if (currentItem == prize && times == 5) {
                clearInterval(time);
                times = 0;
                time = null;
            }
        }, 100);
}
